#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import configparser
import os
import platform

from common.libs.Log import logging
from common.libs.ComDeal import WATER_CMD
from common.libs.ComDeal import ComDeal

from ui.baseSet import Ui_Dialog

class BaseSet(QDialog,Ui_Dialog):

    signal_send = pyqtSignal(str)

    # 硬件版本
    version = '1.0.0'

    # 1mm对应脉冲数
    pulse = 0

    # 通道1刻度系数
    scale_k = 1
    scale_b = 0

    # 通道2刻度系数
    scale_k_2 = 1
    scale_b_2 = 0

    # 漏射线刻度系数
    scale_k_leakage = 1
    scale_b_leakage = 0

    # 紧急停止差值
    task_stop_err= 100

    measure_mode = 'hand'

    # 空气比释动能能量系数关系表
    airKermaPowerTable = {
        "power": [60, 100, 135, 180, 250],
        "Nk": [1, 1, 1, 1, 1],
    }

    # 漏射线能量系数关系表
    leakageRayPowerTable = {
        "power": [60, 100, 135, 180, 250],
        "Nk": [1, 1, 1, 1, 1],
    }

    # 自动测试相关变量
    auto_measure_flag = False
    signal_auto_raido_angle = pyqtSignal()

    def __init__(self,parent=None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)

        self.setWindowIcon(QIcon(':icons/img/info.png'))
        self.setWindowTitle("基本参数设置")
        self.fixSize()

        if platform.system() == "Windows":
            self.configfile = os.getcwd()+'/conf/base.ini'
        elif platform.system() == "Linux":
            self.configfile = '~/conf/base.ini'

        self.pushButton_read.clicked.connect(self.readFlash)
        self.pushButton_write.clicked.connect(self.writeFlash)

        self.pushButton_readConfig.clicked.connect(self.readConfig)
        self.pushButton_saveConfig.clicked.connect(self.writeConfig)

        self.readConfig()

        # 自动测试相关
        self.pushButton_radioAngle_start.clicked.connect(self.autoRadioAngleStart)

    def fixSize(self):
        self.desktop = QApplication.desktop()
 
        #获取显示器分辨率大小
        self.screenRect = self.desktop.screenGeometry()
        self.setFixedSize(self.screenRect.width(),self.screenRect.height())
 
    def readFlash(self):
        cmd = WATER_CMD['数据读取']
        # read_length = 24+8
        # cmd[4] = hex(read_length).replace('0x','').zfill(2)
        cmd[4] = '64'
        new_cmd = ComDeal.getCmd(cmd)
        self.signal_send.emit(new_cmd)

    def writeFlash(self):
        cmd = WATER_CMD['数据写入']
        res = None
        # try:
        res = self.getParameter()
        # except Exception as e:
        #     QMessageBox.information(self, '提示', '%s'%e, QMessageBox.Yes)
        if res:
            cmd[4] = res
            new_cmd = ComDeal.getCmd(cmd)
            self.signal_send.emit(new_cmd)

    def serialDeal(self, cmd, data):
        if cmd == '42':
            QMessageBox.information(self, '提示', '写入参数成功', QMessageBox.Yes)
        if cmd == '43':
            data = data[2:]
            self.setParameter(data)
            QMessageBox.information(self, '提示', '读取参数成功', QMessageBox.Yes)

    def getParameter(self):
        """获取配置参数"""
        # 硬件版本
        version = int(self.lineEdit_version.text().replace('.',''))
        # 测量周期
        period        = round(float(self.comboBox_period.currentText().replace('ms','')))
        # 电机脉冲
        pulse         = round(float(self.doubleSpinBox_pulse.value()))
        measure_speed = round(float(self.doubleSpinBox_measureSpeed.value()))
        move_speed    = round(float(self.doubleSpinBox_moveSpeed.value()))
        f = (72000000/round(pulse)/2)
        measure_speed = f/round(measure_speed)
        move_speed  = f/round(move_speed)

        # 刻度系数
        scale_k = round(float(self.doubleSpinBox_scale_k.value())*100000)
        scale_b = round(float(self.doubleSpinBox_scale_b.value())*100000)
        scale_k_2 = round(float(self.doubleSpinBox_scale_k_2.value())*100000)
        scale_b_2 = round(float(self.doubleSpinBox_scale_b_2.value())*100000)

        scale_k_leakage = round(float(self.doubleSpinBox_scale_k_leakage.value())*100000)
        scale_b_leakage = round(float(self.doubleSpinBox_scale_b_leakage.value())*100000)

        # 空气比释动能能量关系表
        airKermaPowerTable = {
            "Nk":[
                round(float(self.doubleSpinBox_airKerma_Nk_1.value())*1000),
                round(float(self.doubleSpinBox_airKerma_Nk_2.value())*1000),
                round(float(self.doubleSpinBox_airKerma_Nk_3.value())*1000),
                round(float(self.doubleSpinBox_airKerma_Nk_4.value())*1000),
                round(float(self.doubleSpinBox_airKerma_Nk_5.value())*1000),
            ],
            "power":[
                round(self.doubleSpinBox_airKerma_power_1.value()),
                round(self.doubleSpinBox_airKerma_power_2.value()),
                round(self.doubleSpinBox_airKerma_power_3.value()),
                round(self.doubleSpinBox_airKerma_power_4.value()),
                round(self.doubleSpinBox_airKerma_power_5.value()),
            ]
        }

        # 漏射线动能能量关系表
        leakageRayPowerTable = {
            "Nk":[
                round(float(self.doubleSpinBox_leakageRay_Nk_1.value())*1000),
                round(float(self.doubleSpinBox_leakageRay_Nk_2.value())*1000),
                round(float(self.doubleSpinBox_leakageRay_Nk_3.value())*1000),
            ],
            "power":[
                round(self.doubleSpinBox_leakageRay_power_1.value()),
                round(self.doubleSpinBox_leakageRay_power_2.value()),
                round(self.doubleSpinBox_leakageRay_power_3.value()),
            ]
        }

        if measure_speed > 60000 or move_speed > 60000:
            QMessageBox.warning(self,'提示','参数设置错误',QMessageBox.Yes)
            return False
        else:
            cmd_pulse = '{0}{1}{2}{3}'.format(
                hex(round(period)).replace('0x','').zfill(4).upper(),
                hex(round(pulse)).replace('0x','').zfill(4).upper(),
                hex(round(measure_speed)).replace('0x','').zfill(4).upper(),
                hex(round(move_speed)).replace('0x','').zfill(4).upper(),
            )
            cmd_scale = '{0}{1}{2}{3}{4}{5}'.format(
                hex(round(scale_k)).replace('0x','').zfill(8).upper(),
                hex(round(scale_b)).replace('0x','').zfill(8).upper(),
                hex(round(scale_k_2)).replace('0x','').zfill(8).upper(),
                hex(round(scale_b_2)).replace('0x','').zfill(8).upper(),
                hex(round(scale_k_leakage)).replace('0x','').zfill(8).upper(),
                hex(round(scale_b_leakage)).replace('0x','').zfill(8).upper(),
            )
            cmd_leakageRay = '{0}{1}{2}{3}{4}{5}'.format(
                hex(round(leakageRayPowerTable['power'][0])).replace('0x','').zfill(8).upper(),
                hex(round(leakageRayPowerTable['power'][1])).replace('0x','').zfill(8).upper(),
                hex(round(leakageRayPowerTable['power'][2])).replace('0x','').zfill(8).upper(),
                hex(round(leakageRayPowerTable['Nk'][0])).replace('0x','').zfill(8).upper(),
                hex(round(leakageRayPowerTable['Nk'][1])).replace('0x','').zfill(8).upper(),
                hex(round(leakageRayPowerTable['Nk'][2])).replace('0x','').zfill(8).upper(),
            )
            cmd_airKerma = '{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}'.format(
                hex(round(airKermaPowerTable['power'][0])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['power'][1])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['power'][2])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['power'][3])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['power'][4])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['Nk'][0])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['Nk'][1])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['Nk'][2])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['Nk'][3])).replace('0x','').zfill(8).upper(),
                hex(round(airKermaPowerTable['Nk'][4])).replace('0x','').zfill(8).upper(),
            )
            cmd_version = hex(round(version)).replace('0x','').zfill(8).upper()

            cmd = cmd_pulse+cmd_scale+cmd_leakageRay+cmd_airKerma+cmd_version
            _len = hex(round(len(cmd)/2)).replace('0x', '').zfill(2).upper()

            return _len+cmd

    def setParameter(self, data):
        # 电机参数
        self.period = int(data[0:4], 16)
        self.pulse = int(data[4:8], 16)
        f = (72000000/self.pulse/2)
        self.measure_speed = int(f/int(data[8:12], 16))
        self.move_speed = int(f/int(data[12:16], 16))

        # 系数
        self.scale_k = int(data[2*8:3*8], 16)/100000
        self.scale_b = int(data[3*8:4*8], 16)/100000
        self.scale_k_2 = int(data[4*8:5*8], 16)/100000
        self.scale_b_2 = int(data[5*8:6*8], 16)/100000
        self.scale_k_leakage = int(data[6*8:7*8], 16)/100000
        self.scale_b_leakage = int(data[7*8:8*8], 16)/100000

        # 漏射线能量关系表
        self.leakageRayPowerTable['power'] = [
            int(data[8*8:9*8], 16),
            int(data[9*8:10*8], 16),
            int(data[10*8:11*8], 16),
        ]
        self.leakageRayPowerTable['Nk'] = [
            int(data[11*8:12*8], 16)/1000,
            int(data[12*8:13*8], 16)/1000,
            int(data[13*8:14*8], 16)/1000,
        ]
        # 空气比释动能关系表
        self.airKermaPowerTable['power'] = [
            int(data[14*8:15*8], 16),
            int(data[15*8:16*8], 16),
            int(data[16*8:17*8], 16),
            int(data[17*8:18*8], 16),
            int(data[18*8:19*8], 16),
        ]
        self.airKermaPowerTable['Nk'] = [
            int(data[19*8:20*8], 16)/1000,
            int(data[20*8:21*8], 16)/1000,
            int(data[21*8:22*8], 16)/1000,
            int(data[22*8:23*8], 16)/1000,
            int(data[23*8:24*8], 16)/1000,
        ]

        version = str(int(data[24*8:25*8], 16))
        self.version = version[0] + '.' + version[1] + '.' + version[2] 

        for i in range(0,self.comboBox_period.count()):
            if self.comboBox_period.itemText(i) == '%sms'%self.period:
                self.comboBox_period.setCurrentIndex(i)
                break
        self.doubleSpinBox_pulse.setValue(self.pulse)
        self.doubleSpinBox_measureSpeed.setValue(self.measure_speed)
        self.doubleSpinBox_moveSpeed.setValue(self.move_speed)
        self.doubleSpinBox_scale_k.setValue(self.scale_k)
        self.doubleSpinBox_scale_b.setValue(self.scale_b)
        self.doubleSpinBox_scale_k_2.setValue(self.scale_k_2)
        self.doubleSpinBox_scale_b_2.setValue(self.scale_b_2)
        self.doubleSpinBox_scale_k_leakage.setValue(self.scale_k_leakage)
        self.doubleSpinBox_scale_b_leakage.setValue(self.scale_b_leakage)
        # 空气比释动能
        self.doubleSpinBox_airKerma_power_1.setValue(self.airKermaPowerTable['power'][0])
        self.doubleSpinBox_airKerma_power_2.setValue(self.airKermaPowerTable['power'][1])
        self.doubleSpinBox_airKerma_power_3.setValue(self.airKermaPowerTable['power'][2])
        self.doubleSpinBox_airKerma_power_4.setValue(self.airKermaPowerTable['power'][3])
        self.doubleSpinBox_airKerma_power_5.setValue(self.airKermaPowerTable['power'][4])
        self.doubleSpinBox_airKerma_Nk_1.setValue(self.airKermaPowerTable['Nk'][0])
        self.doubleSpinBox_airKerma_Nk_2.setValue(self.airKermaPowerTable['Nk'][1])
        self.doubleSpinBox_airKerma_Nk_3.setValue(self.airKermaPowerTable['Nk'][2])
        self.doubleSpinBox_airKerma_Nk_4.setValue(self.airKermaPowerTable['Nk'][3])
        self.doubleSpinBox_airKerma_Nk_5.setValue(self.airKermaPowerTable['Nk'][4])
        # 漏射线
        self.doubleSpinBox_leakageRay_power_1.setValue(self.leakageRayPowerTable['power'][0])
        self.doubleSpinBox_leakageRay_power_2.setValue(self.leakageRayPowerTable['power'][1])
        self.doubleSpinBox_leakageRay_power_3.setValue(self.leakageRayPowerTable['power'][2])
        self.doubleSpinBox_leakageRay_Nk_1.setValue(self.leakageRayPowerTable['Nk'][0])
        self.doubleSpinBox_leakageRay_Nk_2.setValue(self.leakageRayPowerTable['Nk'][1])
        self.doubleSpinBox_leakageRay_Nk_3.setValue(self.leakageRayPowerTable['Nk'][2])
        # 版本
        self.lineEdit_version.setText(self.version)

    def writeConfig(self):
        """写入配置文件中"""
        try:
            config = configparser.RawConfigParser()
            # 添加condition选项
            self.task_stop_err = int(self.lineEdit_taskStopErr.text())
            if self.radioButton_auto.isChecked():
                self.measure_mode = 'auto'
            if self.radioButton_hand.isChecked():
                self.measure_mode = 'hand'
            config.add_section("base")
            config.set("base", "task_stop_err", str(self.task_stop_err))
            config.set("base", "measure_mode", str(self.measure_mode))
            # 写入并保存文件到当前项目文件夹下
            with open(self.configfile, 'w') as configfile:
                config.write(configfile)
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
        except Exception as e:
            QMessageBox.warning(self,"错误","%s"%e, QMessageBox.Yes)

    def readConfig(self):
        pass
        try:
            config = configparser.ConfigParser()
            config.read(self.configfile)
            return
            print(self.configfile)
            print(config)
            base = config['base']

            # self.task_stop_err = int(config['base']['task_stop_err'])
            self.task_stop_err = int(base['task_stop_err']) if 'task_stop_err' in base else 100
            self.lineEdit_taskStopErr.setText(str(self.task_stop_err))

            self.measure_mode = base['measure_mode'] if 'measure_mode' in base else 'hand'
            if self.measure_mode == "hand":
                self.radioButton_hand.setChecked(True)
            if self.measure_mode == "auto":
                self.radioButton_auto.setChecked(True)
        except Exception as e:
            QMessageBox.warning(self, "错误", "%s" % e, QMessageBox.Yes)

    def autoRadioAngleStart(self):
        self.auto_measure_flag = True
        self.spinBox_radioAngle_cnt.setValue(0)
        self.signal_auto_raido_angle.emit()
